import 'dart:async';
import 'package:ati_package/core/utils/ati_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class GetCodeButton extends StatefulWidget {
  final Future<bool> Function()? onSend; // 点击发送时回调（返回 true 表示发送成功）
  final int countdownSeconds;
  final String normalText;
  final String sendingText;
  final Color activeColor;
  final Color disableColor;

  const GetCodeButton({
    super.key,
    this.onSend,
    this.countdownSeconds = 60,
    this.normalText = '获取验证码',
    this.sendingText = '重新发送',
    this.activeColor = const Color(0xFF059B4F),
    this.disableColor = const Color(0xFFBDBDBD),
  });

  @override
  State<GetCodeButton> createState() => _GetCodeButtonState();
}

class _GetCodeButtonState extends State<GetCodeButton> {
  Timer? _timer;
  int _remaining = 0;
  bool get _isCounting => _remaining > 0;

  void _startCountdown() {
    setState(() => _remaining = widget.countdownSeconds);
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_remaining <= 1) {
        timer.cancel();
        setState(() => _remaining = 0);
      } else {
        setState(() => _remaining--);
      }
    });
  }

  Future<void> _handleSend() async {
    if (_isCounting) return;
    if (widget.onSend != null) {
      bool success = await widget.onSend!();
      if (success) {
        _startCountdown();
      }
    } else {
      _startCountdown();
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _isCounting ? null : _handleSend,
      child: Container(
        height: 30.r,
        constraints: BoxConstraints(
          minWidth: 20.r,
          minHeight: 20.r,
          maxWidth: 85.r,
          maxHeight: 27.5.r,
        ),
        alignment: Alignment.center,
        margin: EdgeInsets.only(right: 12.5.r),
        padding: EdgeInsets.symmetric(horizontal: 5.r),
        decoration: BoxDecoration(
          border: Border.all(
            width: 1.r,
            color: _isCounting ? AtiColor.textGreyColor : AtiColor.primary,
          ),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Text(
          _isCounting
              ? '${widget.sendingText} (${_remaining}s)'
              : widget.normalText,
          style: TextStyle(
            color: _isCounting ? AtiColor.textGreyColor : AtiColor.primary,
            fontSize: 10.r,
          ),
        ),
      ),
    );
  }
}
